package com.cwf.security.service.impl;


import com.cwf.security.dao.LoginDao;
import com.cwf.security.dao.UserLoginDao;
import com.cwf.security.entity.SecurityUser;
import com.cwf.security.entity.User;
import com.cwf.security.entity.UserLogin;
import com.cwf.security.service.PermissionListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @description SpringSecurity	UserDetailsService 实现类
 * @author  18068
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    UserLoginDao loginDao;

    @Autowired
    PermissionListService permissionListService;

    @Autowired
    PasswordEncoder passwordEncoder;


    @Override
    public UserDetails loadUserByUsername(String loginName) {


        UserLogin user = loginDao.userDetails(loginName);


        System.out.println(user);


        List<String> permissionList = null;

//        try {
//             permissionList = Optional.ofNullable(user).map(v -> {
//                //获取当前用户权限列表
//                List<String> permissions = permissionListService.permissionList(user.getId());
//
//                if (permissions.size()!=0) return permissions;
//
//                return new ArrayList<String>();
//                //处理
//            }).get();
//
//             log.info("\n当前用户用户名: {}",loginName);
//             log.info("\n当前登录用户获取权限列: {}",permissionList);
//
//            //redis权限列表缓存
//            String key = "permission:"+user.getId();
//
//            try {
//                redisTemplate.opsForValue().set(key,permissionList);
//            }catch (Exception e){
//                log.error("id为{}的用户缓存权限列表失败,请检查redis是否正常",user.getId());
//            }
//
//        }catch (Exception e){
//            log.error("\n当前登录用户获取权限列表异常");
//        }



        return new SecurityUser(user,permissionList,null);
    }
}
